package com.yili.userservice.controller;

import com.yili.common.result.Result;
import com.yili.model.entity.UserAddress;
import com.yili.userservice.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addresses")
public class UserAddressController {

    @Autowired
    private UserAddressService userAddressService;

    @GetMapping
    public Result<List<UserAddress>> getUserAddresses(@RequestHeader("X-User-Id") Long userId) {
        List<UserAddress> addresses = userAddressService.getUserAddresses(userId);
        return Result.ok(addresses);
    }

    @PostMapping
    public Result<UserAddress> addUserAddress(@RequestHeader("X-User-Id") Long userId, @RequestBody UserAddress address) {
        address.setUserId(userId);
        UserAddress savedAddress = userAddressService.addUserAddress(address);
        return Result.ok(savedAddress);
    }

    @PutMapping("/{id}")
    public Result<UserAddress> updateUserAddress(@RequestHeader("X-User-Id") Long userId, 
                                               @PathVariable Long id, 
                                               @RequestBody UserAddress address) {
        address.setUserId(userId);
        UserAddress updatedAddress = userAddressService.updateUserAddress(id, address);
        return Result.ok(updatedAddress);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteUserAddress(@RequestHeader("X-User-Id") Long userId, @PathVariable Long id) {
        userAddressService.deleteUserAddress(id);
        return Result.ok("删除成功");
    }

    @PostMapping("/{id}/default")
    public Result<Void> setDefaultAddress(@RequestHeader("X-User-Id") Long userId, @PathVariable Long id) {
        userAddressService.setDefaultAddress(userId, id);
        return Result.ok("设置成功");
    }
}